package org.pzy.java.json;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: DRevelation
 * @Date: 2022/6/17 10:55
 */
public class GsonDemo {
    public static void main(String[] args) {

        List<String> books = new ArrayList<>();
        books.add("Java");
        books.add("Go");
        User user = User.builder().id(1).name("abc").email("abc@123.com").books(books).other(123L).build();

        Gson gson = new Gson();
        String str = gson.toJson(user);
        System.out.println("str = " + str);

        User user1 = gson.fromJson(str, User.class);
        System.out.println("user1 = " + user1);

        JsonObject jsonObject = gson.fromJson(str, JsonObject.class);
        System.out.println("name = " + jsonObject.get("name").getAsString());

        JsonArray books1 = jsonObject.getAsJsonArray("books");
        System.out.println("books1 = " + books1);
        System.out.println("books1[0] = " + books1.get(0).getAsString());
    }
}
